package net.xuele.learn.testClass;

import java.util.concurrent.locks.StampedLock;

public class Point {
    private int x, y;
    final StampedLock lock = new StampedLock();
    public int distanceFromOrigin() {
        // 乐观读
        long stamp = lock.tryOptimisticRead();
        // 读入局部变量，读入的过程中有可能被修改
        int curX = x, curY = y;
        // 判断执行读操作期间，是否存在写的操作，如果存在，则生机为悲观读锁
        if (!lock.validate(stamp)) {
            // 升级为悲观读锁
            stamp = lock.readLock();
            try {
                curX = x;
                curY = y;
            } finally {
                // 释放悲观读锁
                lock.unlockRead(stamp);
            }
        }
        return (int) Math.sqrt(curX * curX + curY * curY);
    }
}
